package Demo33;

class Solution {
    public int[][] matrixBlockSum(int[][] mat, int k) {
        int hight = mat.length;
        int len = mat[0].length;
        int[][] dp = new int[hight+1][len+1];
        // 初始化dp表
        for (int i = 1; i < hight + 1; i++) {
            for (int j = 1; j < len + 1; j++) {
                dp[i][j] = dp[i - 1][j] + dp[i][j-1] - dp[i-1][j -1] + mat[i-1][j-1];
            }
        }
        // 使用dp表
        int[][] ret = new int[hight][len];
        for (int i = 0; i < hight; i++) {
            for (int j = 0; j < len; j++) {
                int x1 = Math.max(0,i - k) + 1;
                int y1 = Math.max(0,j - k) + 1;
                int x2 = Math.min(hight - 1,i + k) + 1;
                int y2 = Math.min(len - 1,j + k) + 1;
                ret[i][j] = dp[x2][y2] - dp[x1 - 1][y2] - dp[x2][y1 - 1] + dp[x1 - 1][y1 - 1];
            }
        }
        return ret;
    }
}
class Demo {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] ret = solution.matrixBlockSum(new int[][] {{1,2,3},{4,5,6},{7,8,9}},1);
        for (int i = 0; i < ret.length; i++) {
            for (int j = 0; j < ret.length; j++) {
                System.out.print(ret[i][j] + "  ");
            }
            System.out.println();
        }
    }
}